
// 百度云  设备身份三元组
const Baiduyun_deviceConfig = {
  IoTCoreID: "addleaw",
  Devicekey: "zhjt",
  deviceSecret: "QVrJxmVbGjUhwlok",
  MqttUserName: "thingidp@addleaw|zhjt|0|MD5",
  MqttUserPasswd: "ca5812f96b39cb117d5a72618c5f4cf3",
  MqttClientID: "zhjt22"
};

// 加载库
const util = require('../../utils/util.js')
var mqtt = require('../../utils/mqtt.js')

var client
Page({
  data: {
    temperature: '0',
    humidity: '0',
    fan: '0',
    fan_status: '?',
    beep: '0',
    beep_status: '?'
  },
//LED1开关响应函数
onled1Change: function(event) {
  var that = this
    console.log(event.detail)
    let sw = event.detail.value
    // 要发布的主题
    let topic = `$iot/${Baiduyun_deviceConfig.Devicekey}/user/control`;
    if (sw) {
      client.publish(topic, '{"led1":1}', function (err) {
        if (!err) {
          console.log('成功下发命令 开led1!')
          that.setData({
            fan_status: '开'
          })
        }
      })
    } else {
      client.publish(topic, '{"led1":0}', function (err) {
        if (!err) {
          console.log('成功下发命令 关led1!')
        }
      })
    }
},
//LED2开关响应函数
onled2Change: function(event) {
  var that = this
    console.log(event.detail)
    let sw = event.detail.value
    // 要发布的主题
    let topic = `$iot/${Baiduyun_deviceConfig.Devicekey}/user/control`;
    if (sw) {
      client.publish(topic, '{"led2":1}', function (err) {
        if (!err) {
          console.log('成功下发命令 开led2!')
          that.setData({
            fan_status: '开'
          })
        }
      })
    } else {
      client.publish(topic, '{"led2":0}', function (err) {
        if (!err) {
          console.log('成功下发命令 关led2!')
        }
      })
    }
},
//LED3开关响应函数
onled3Change: function(event) {
  var that = this
    console.log(event.detail)
    let sw = event.detail.value
    // 要发布的主题
    let topic = `$iot/${Baiduyun_deviceConfig.Devicekey}/user/control`;
    if (sw) {
      client.publish(topic, '{"led3":1}', function (err) {
        if (!err) {
          console.log('成功下发命令 开led3!')
          that.setData({
            fan_status: '开'
          })
        }
      })
    } else {
      client.publish(topic, '{"led3":0}', function (err) {
        if (!err) {
          console.log('成功下发命令 关led3!')
        }
      })
    }
},
  // 风扇开关的响应函数
  onFanChange: function(event) {
    var that = this
    console.log(event.detail)
    let sw = event.detail.value
    // 要发布的主题
    let topic = `$iot/${Baiduyun_deviceConfig.Devicekey}/user/control`;
    if (sw) {
      client.publish(topic, '{"fan":255}', function (err) {
        if (!err) {
          console.log('成功下发命令 开风扇!')
          that.setData({
            fan_status: '开'
          })
        }
      })
    } else {
      client.publish(topic, '{"fan":0}', function (err) {
        if (!err) {
          console.log('成功下发命令 关风扇!')
          that.setData({
            fan_status: '关'
          })
        }
      })
    }
  },

  // 报警器开关的响应函数
  onBeepChange: function(event) {
    var that = this
    console.log(event.detail)
    let sw = event.detail.value
    let topic = `$iot/${Baiduyun_deviceConfig.Devicekey}/user/control`;
    if (sw) {
      client.publish(topic, '{"beep":1}', function (err) {
        if (!err) {
          console.log('成功下发命令 开蜂鸣器!')
          that.setData({
            beep_status: '开'
          })
        }
      })
    } else {
      client.publish(topic, '{"beep":0}', function (err) {
        if (!err) {
          console.log('成功下发命令 关蜂鸣器!')
          that.setData({
            beep_status: '关'
          })
        }
      })
    }
  },

  // 设备上线 按钮点击事件
  online: function (e) {
    this.doConnect()
  },
  doConnect() { 
    var that = this
    const options = that.baiduyun_initMqttOptions(Baiduyun_deviceConfig)
    console.log(options)
    
    let baiyun_serverAddess = `wxs://${Baiduyun_deviceConfig.IoTCoreID}.iot.gz.baidubce.com/mqtt`    // 百度云物联网平台
    client = mqtt.connect(baiyun_serverAddess, options)
    client.on('connect', function () {
      console.log('连接服务器成功')
      let dataTime = util.formatTime(new Date());
      that.setData({
        deviceState: dataTime + ' Connect Success!'
      })
      client.subscribe('$iot/zhjt/user/fortest',{qos:0},function(err){
        if(!err){
          console.log("订阅成功")
        }
      })
      client.on('message',function(topic,message,packet){
        let recvstr = packet.payload.toString()
        console.log(recvstr)
        var jsonObj = JSON.parse(recvstr);
        console.log(jsonObj)
        console.log(jsonObj.temperature)
        that.setData({
          temperature: jsonObj.temperature,
          humidity: jsonObj.humidity
        })
      })
    })
  },

  //IoT平台mqtt连接参数初始化
  baiduyun_initMqttOptions(Baiduyun_deviceConfig) {
    const params = {
      ioTCoreID: Baiduyun_deviceConfig.IoTCoreID,
      deviceKey: Baiduyun_deviceConfig.Devicekey,
      deviceSecret: Baiduyun_deviceConfig.deviceSecret,
      username: Baiduyun_deviceConfig.MqttUserName,
      password: Baiduyun_deviceConfig.MqttUserPasswd,
      clientId: Baiduyun_deviceConfig.MqttClientID,
    }

    // CONNECT参数
    const options = {
      keepalive: 60, // 60s
      clean: true, // cleanSession不保持持久会话
      protocolVersion: 4 // MQTT v3.1.1
    }

    //1.生成clientId，username，password

    options.username = `${params.username}`
    options.password = `${params.password}`
    options.clientId = `${params.clientId}`
  
    return options;
  },
  
  // 设备下线 按钮点击事件
  offline: function () {
    var that = this;
    client.end()  // 关闭连接
    console.log('服务器连接断开')
    let dateTime = util.formatTime(new Date());
    that.setData({
      deviceState: dateTime + ' Disconnect!'
    })
  }
})

